package com.jiufengxinxi.ts.common.utils.printer;
import java.util.List;

import javax.usb.*;


public class ConnectUsbEqu {
	public ConnectUsbEqu(short pid, short vid) {
		  try {
	           this.idProduct = pid;
	           this.idVendor  = vid;
	           this.useUsb();
	       }catch (Exception e ){
	           System.out.println("与打印机建立连接失败。erro:"+e);
	       }
	}

	private UsbPipe sendUsbPipe;
	private UsbPipe receivedUsbPipe;

    private UsbInterface usbiface;
	  //USB设备的 VID  PID
    private short idVendor = (short)0x28e9;
    private short idProduct = (short)0x5812;
 
//    public static void main(String[] args) {
//        try {
//            UsbPipe sendUsbPipe = new ConnectUsbEqu().useUsb();
//            Image img = Toolkit.getDefaultToolkit().getImage("/home/jfxx/img.png");
//            BufferedImage bi_scale = ImageUtil.toBufferedImage(img);
//            sendMassge(PicFromPrintUtils.draw2PxPoint2(bi_scale));
////            byte[] size = EscPosAdapter.fontSizeSetBig(2);
////            sendMassge(size);
//            sendMassge(EscPosAdapter.feedPaperCutPartial());
//        
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
 

public UsbPipe useUsb() throws Exception{
        UsbInterface iface = linkDevice();
        if (iface == null) {
            return null;
        }
        UsbEndpoint receivedUsbEndpoint,sendUsbEndpoint;
 
        sendUsbEndpoint = (UsbEndpoint)iface.getUsbEndpoints().get(0);
        if (!sendUsbEndpoint.getUsbEndpointDescriptor().toString().contains("OUT")) {
            receivedUsbEndpoint = sendUsbEndpoint;
            sendUsbEndpoint = (UsbEndpoint)iface.getUsbEndpoints().get(1);
        } else {
            receivedUsbEndpoint = (UsbEndpoint)iface.getUsbEndpoints().get(1);
        }
 
        //发送：
        sendUsbPipe =  sendUsbEndpoint.getUsbPipe();
        sendUsbPipe.open();
 
        //接收
         receivedUsbPipe =  receivedUsbEndpoint.getUsbPipe();
         receivedUsbPipe.open();
// 
//        new Thread(new Runnable() {
//            public void run() {
//                try {
//                    receivedMassge(receivedUsbPipe);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
        return sendUsbPipe;
    }
 
public UsbInterface linkDevice() throws Exception{
 
        UsbDevice device = null;
        if (device == null) {
            device = findDevice(UsbHostManager.getUsbServices()
                    .getRootUsbHub());
        }

        if (device == null) {
            System.out.println("设备未找到！");
            return null;
        }
        UsbConfiguration configuration = device.getActiveUsbConfiguration();
        UsbInterface iface = null;
        if (configuration.getUsbInterfaces().size() > 0) {
            //此处需要注意 本人在这个地方的时候是进行了debug来看设备到底在map中的key是多少
            //各位如果在此处获取不到设备请自行进行debug看map中存储的设备key到底是多少
            iface = configuration.getUsbInterface((byte) 0);
        } else {
            return null;
        }

        usbiface = iface;

        iface.claim(/*new UsbInterfacePolicy()
        {
            @Override
            public boolean forceClaim(UsbInterface usbInterface)
            {
                return true;
            }
        }*/);


        return iface;
    }
 
public void receivedMassge() throws Exception{
        StringBuffer all = new StringBuffer();
        byte[] b = new byte[64];
        int length;
        while (true) {
            length = receivedUsbPipe.syncSubmit(b);//阻塞
            System.out.println("接收长度：" + length);
            for (int i = 0; i < length; i++) {
                //此处会打印所有的返回值 注意返回值全部也都是16进制的
                //比如读取卡号或者身份证号时需要自行转换回10进制
                //并进行补0操作,比如01转换为10进制会变成1需要补0 变成01
                //不然得到的10进制返回值会有问题
                System.out.print(Byte.toUnsignedInt(b[i])+" =====================================");
                all.append(Byte.toUnsignedInt(b[i])+" ");
            }
        }
    }

    public String receivedData()throws Exception{
        StringBuffer all = new StringBuffer();
        byte[] b = new byte[64];
        int length = receivedUsbPipe.syncSubmit(b);//阻塞
        System.out.println("接收长度：" + length);
        for (int i = 0; i < length; i++) {
            //此处会打印所有的返回值 注意返回值全部也都是16进制的
            //比如读取卡号或者身份证号时需要自行转换回10进制
            //并进行补0操作,比如01转换为10进制会变成1需要补0 变成01
            //不然得到的10进制返回值会有问题
            System.out.print(Byte.toUnsignedInt(b[i])+" =====================================");
            all.append(Byte.toUnsignedInt(b[i])+" ");
        }
        return all.toString();
    }
 
public  boolean sendMassge(byte[] buff) throws UsbDisconnectedException, UsbException {
       	if(sendUsbPipe !=null) {
       		sendUsbPipe.syncSubmit(buff);//阻塞
       		return true;
       	}else {
       		System.out.println("未与打印机建立连接");
       		return false;
       	}



//        usbPipe.asyncSubmit(buff);//非阻塞
    }
public  boolean sendMassge(byte[] buff, int leng)  throws UsbDisconnectedException, UsbException{
   	if(sendUsbPipe !=null) {
   		sendUsbPipe.syncSubmit(buff);//阻塞
   		return true;
   	}else {
   		System.out.println("未与打印机建立连接");
   		return false;
   	}
    
    
//    usbPipe.asyncSubmit(buff);//非阻塞
}
public  boolean sendMassge(String buff)  throws UsbDisconnectedException, UsbException{
	if(sendUsbPipe !=null) {
		sendUsbPipe.syncSubmit(buff.getBytes());//阻塞
   		return true;
   	}else {
   		System.out.println("未与打印机建立连接");
   		return false;
   	}
//    usbPipe.asyncSubmit(buff);//非阻塞
}
public  boolean sendMassge(int buff)  throws UsbDisconnectedException, UsbException{
   	if(sendUsbPipe !=null) {
   		sendUsbPipe.syncSubmit(String.valueOf(buff).getBytes());//阻塞
   		return true;
   	}else {
   		System.out.println("未与打印机建立连接");
   		return false;
   	}

}
public UsbDevice findDevice(UsbHub hub)
    {
        UsbDevice device = null;
        List list = (List) hub.getAttachedUsbDevices();
        for (int i = 0;i<list.size();i++)
        {
            device = (UsbDevice)list.get(i);
            UsbDeviceDescriptor desc = device.getUsbDeviceDescriptor();
            System.out.println(i+"___"+desc.idVendor()+"___"+desc.idProduct());
            if (desc.idVendor() == idVendor && desc.idProduct() == idProduct) {return device;}
            if (device.isUsbHub()){
                device = findDevice((UsbHub) device);
                if (device != null) return device;
            }
        }
        return null;
    }

    public void disconnection(){
        try {
            sendUsbPipe.close();
        } catch (UsbException e) {
            e.printStackTrace();
        }
        try {
            receivedUsbPipe.close();
            usbiface.release();
        } catch (UsbException e) {
            e.printStackTrace();
        }
    }

    public boolean isOpen(){
        return sendUsbPipe!=null&&sendUsbPipe.isOpen();
    }

}
